package com.ysw.wisdomcampus.fragment

import android.app.AlertDialog
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.get
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.ysw.wisdomcampus.LoginActivity
import com.ysw.wisdomcampus.R
import com.ysw.wisdomcampus.kt.start
import com.ysw.wisdomcampus.model.projectModel
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.URL


class PersonalFragment : PreferenceFragmentCompat() {

    private lateinit var numPref: Preference
    private lateinit var name: Preference
    private lateinit var cellPhone: Preference
    private lateinit var sex: Preference
    private lateinit var major: Preference
    private lateinit var top: Preference
    private lateinit var exit: Preference
    private val CLICK = Preference.OnPreferenceClickListener {
        projectModel.toast("${it.title} : ${it.summary}")
        true
    }

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.personal, rootKey)
        numPref = findPreference<Preference>("id")!!
        name = findPreference<Preference>("name")!!
        sex = findPreference<Preference>("sex")!!
        major = findPreference<Preference>("major")!!
        cellPhone = findPreference("cellPhone")!!
        top = findPreference("top")!!
        exit = findPreference("exit")!!
    }

    override fun onResume() {
        super.onResume()
        projectModel.activeStudent?.let {
            numPref.summary = it.studentId
            name.summary = it.name
            sex.summary = it.sex
            major.summary = it.major
            cellPhone.summary = it.cellNum
        }

        exit.setOnPreferenceClickListener {
            AlertDialog.Builder(requireContext()).apply {
                setTitle("退出登录")
                setMessage("确定退出登录吗？")
                setPositiveButton("确定") { v, d ->
                    v.dismiss()
                    start(
                        requireContext(),
                    ) {
                        Intent(requireContext(), LoginActivity::class.java)
                    }
                }
                setNegativeButton("我在想想") { v, d ->
                    v.dismiss()
                }
                create()
                show()
            }
            true
        }

        numPref.onPreferenceClickListener = CLICK
        name.onPreferenceClickListener = CLICK
        sex.onPreferenceClickListener = CLICK

        major.setOnPreferenceClickListener {
            showDialog("major")
            true
        }

        cellPhone.setOnPreferenceClickListener {
            showDialog("cellNum")
            true
        }

        GlobalScope.launch(Dispatchers.Main) {
            val drawable = withContext(Dispatchers.IO) {
                return@withContext getIcon(projectModel.activeStudent!!.icon)
            }
            top.icon = drawable
        }
    }

    private fun getIcon(url: String): Drawable {
        val urls = URL(url).openConnection()
        return Drawable.createFromStream(urls.getInputStream(), "pic")
    }

    fun showDialog(
        condition: String,
    ) {
        val title = when (condition) {
            "cellNum" -> "通讯号码"
            "major" -> "专业"
            else -> "修改内容"
        }
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.edit_dialog, null)
        AlertDialog.Builder(requireContext()).setView(view).create().apply {
            view.findViewById<TextView>(R.id.title).text = "修改[$title]"
            view.findViewById<TextView>(R.id.cancle).setOnClickListener { dismiss() }
            view.findViewById<TextView>(R.id.confirm).setOnClickListener {
                val modificationText = findViewById<EditText>(R.id.edit).text.toString()
                if (modificationText != "") {
                    projectModel.apply {
                        GlobalScope.launch(Dispatchers.Main) {
                            withContext(Dispatchers.IO) {
                                update(
                                    studentId = activeStudent!!.studentId,
                                    condition = condition,
                                    modification = modificationText,
                                )
                            }
                            projectModel.activeStudent?.let {
                                numPref.summary = it.studentId
                                name.summary = it.name
                                sex.summary = it.sex
                                major.summary = it.major
                                cellPhone.summary = it.cellNum
                            }
                            projectModel.toast("修改 $title 成功！")
                        }

                    }
                }
                dismiss()
            }
            show()
            window!!.setLayout(
                requireContext().resources.displayMetrics.widthPixels - 30,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
        }
    }
}